<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use think\facade\View;

class Product extends Base {

    public function index() {

        $params = $this->request->param(["title", "time"], "trim");
        $page = $this->request->param("page", 1, "intval");

        $result = [];
        try{
            $result = (new \app\business\Product())->pageList($page, $params);
        }catch (Exception $e){
            Log::error($e);
        }
        return View::fetch("", [
            "productList" => $result
        ]);
    }

    public function add() {
        return View::fetch();
    }


    public function save() {
        if (!$this->request->isPost()) {
            return show(config("status.error"), "请求方式不正确");
        }
        $params = $this->request->param([
            "id",
            "title",
            "category_id",
            "category_path_id",
            "promotion_title",
            "sku",
            "url_key",
            "unit",
            "keywords",
            "sub_title",
            "stock",
            "price",
            "cost_price",
            "is_show_stock",
            "spec_type",
            "big_img",
            "recommend_img",
            "carousel_img",
            "description",
            "is_home_recommend",
            "status",
            "skus",
            "add_spec_arr"
        ], "", "trim");

        $categoryIdPath = $params["category_path_id"];
        $categoryIdPathArr = explode(",", 0);
        $params["category_id"] = end($categoryIdPathArr);
        try{
             validate(\app\admin\validate\Product::class)->check($params);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getMessage());
        }

        try{
            $result = (new \app\admin\business\Product())->save($params);
            if ($result == false) {
                return show(config("status.error"), "保存失败");
            }
        }catch (Exception $e){
            return show(config("status.error"), $e->getMessage());
        }

        return show(config("status.success"), "保存成功");
    }

}